package com.soup.lab.basic.iso;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
public class IsolateTaskSchedulerTestCase {

    @Test
    public void test() throws InterruptedException {
        IsolateTaskScheduler<Integer, String> scheduler = new IsolateTaskScheduler<>(new TaskSourceImpl(), v -> {
            log.info("--> {}", v);
            try {
                Thread.sleep(new Random().nextInt(10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        scheduler.start();
        TimeUnit.MINUTES.sleep(5);
    }

    static class TaskSourceImpl implements TaskSource<Integer, String> {

        private Map<Integer, Integer> indexMap = new ConcurrentHashMap<>();

        @Override
        public List<Integer> keys() {
            return IntStream.range(0, 16).boxed().collect(Collectors.toList());
        }

        @Override
        public List<String> fetchByKey(Integer key) {
            if(Math.random() > 0.5) {
                return Collections.emptyList();
            }
            Integer index = indexMap.getOrDefault(key, 0);
            List<String> result = new ArrayList<>();
            for(int i = 0; i < 20; i++) {
                result.add(String.valueOf((index++)*16 + key));
            }
            indexMap.put(key, index);
            return result;
        }
    }

}
